package com.example.system.controller;

import com.example.system.service.impl.InvitationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.Map;
import java.util.concurrent.*;

@Controller
public class RecordsCountWebSocketController {

    @Autowired
    private final SimpMessagingTemplate messagingTemplate;

    @Autowired
    InvitationServiceImpl invitationService;

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

    private final Map<Integer, ScheduledFuture<?>> processesOfRecordsCount = new ConcurrentHashMap<>();

    public RecordsCountWebSocketController(SimpMessagingTemplate messagingTemplate, InvitationServiceImpl invitationService) {
        this.messagingTemplate = messagingTemplate;
        this.invitationService = invitationService;
    }

    @MessageMapping("/startGettingRecordsCount")
    public void startGettingRecordsCount(@Payload Integer userId) {
        if (processesOfRecordsCount.containsKey(userId)) {
            return;
        }
        Runnable task = () -> {
            System.out.println("Getting records count of ID: " + userId);
            try {
                TimeUnit.SECONDS.sleep(1); // 模拟任务执行时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            Integer recordsCount = invitationService.getAllNewInviteeRecordsCountByUserId(userId);
            messagingTemplate.convertAndSend("/topic/getRecordsCount/" + userId, recordsCount);
        };
        ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
        processesOfRecordsCount.put(userId, future);
    }

    @MessageMapping("/stopGettingRecordsCount")
    public void stopHealthPushing(@Payload Integer userId) {
        ScheduledFuture<?> future = processesOfRecordsCount.remove(userId);
        if (future != null && !future.isDone()) {
            future.cancel(false);
        }
    }
}